package com.fly.core.aspect;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fly.show.model.JsonResult;

/**
 * aop包装接口调用结果
 *
 * @author 00fly
 * @version [版本号, 2022年3月10日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Aspect
@Component
public class WrapCalledAspect
{
    private Pattern pattern = Pattern.compile("\\B(\\p{Upper})(\\p{Lower}*)");
    
    private Type LIST_MAP_STRING_OBJECT = new TypeReference<List<Map<String, Object>>>()
    {
    }.getType();
    
    /**
     * 驼峰转下划线并大写
     * 
     * @param input
     * @return
     * @see [类、类#方法、类#成员]
     */
    private String camelCaseToLineUpperCase(String input)
    {
        return pattern.matcher(input).replaceAll("_$1$2").toUpperCase();
    }
    
    @Around("execution(* com.fly.show.api.RestUserController.toAll(..))")
    public Object around(ProceedingJoinPoint joinPoint)
        throws Throwable
    {
        Object object = joinPoint.proceed();
        return JsonResult.success(object);
    }
    
    @Around("execution(* com.fly.show.api.RestUserController.jsonAll(..))")
    public Object around2(ProceedingJoinPoint joinPoint)
        throws Throwable
    {
        Object object = joinPoint.proceed();
        if (object instanceof JsonResult)
        {
            List<Map<String, Object>> list2 = new ArrayList<>();
            Map<String, Object> map2;
            JsonResult<?> result = (JsonResult<?>)object;
            Object data = result.getData();
            if (data instanceof List<?>)
            {
                String jsonStr = JSONObject.toJSONString(data);
                List<Map<String, Object>> list = JSONObject.parseObject(jsonStr, LIST_MAP_STRING_OBJECT);
                for (Map<String, Object> map : list)
                {
                    map2 = new HashMap<>();
                    for (String key : map.keySet())
                    {
                        map2.put(camelCaseToLineUpperCase(key), map.get(key));
                    }
                    list2.add(map2);
                }
            }
            object = JsonResult.success(list2);
        }
        return object;
    }
}
